<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    header {
      display: flex;
      min-width: 750px;
      margin: auto;
      padding: 5px 20px;
      color: #FF3E00;
      background-color: #EAE8EB;
      justify-content: space-between;
      align-items: center;
    }

    img {
      width: 80px;
      border-radius: 50%;
    }

    table {
      width: 80%;
      margin: auto;
      min-width: 750px;
      margin-top: 50px;

    }

    td {
      width: 25%;
      text-align: center;
    }

    #del {
      width: 50px;
      height: 30px;
      background-color: #FF3E00;
      color: #fff;
      border: 0;
      cursor: pointer;
    }

    #del:active {
      background-color: orange;
    }
  </style>
</head>

<body>
  <header>
    <h3> 欢迎：<span id="username"></span></h3> <img src="" alt="" id="img">
  </header>
  <table border="1px" id="table">

  </table>
</body>
<script>
  fetch("/api")
    .then(res => res.json())
    .then(res => {
      render(res)
    })
  username.innerHTML = localStorage.getItem("username")
  img.src = localStorage.getItem("avatar")
  function render(arr) {
    table.innerHTML = arr.map((item, index) => ` 
    <tr id='${item._id}' data-src='${item.avatar}'>
      <td>${index}</td>
      <td>${item.username}</td>
      <td><img src="${item.avatar}" alt=""></td>
      <td><button id='del'>del</button></td>
    </tr>
    `).join("")
  }
  table.onclick = (e) => {
    if (e.target.nodeName === "BUTTON") {
      const parent = e.target.parentNode.parentNode
      const src = parent.dataset.src
      // 发请求删除对应数据库的内容
      fetch(`/api?id=${parent.id}&src=${src} `, { method: 'delete' })
        .then(res => res.json()).then(res => {
          // 删除对应的tr 
          res.ok && parent.remove()
        })
    }
  }
</script>

</html>